package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadServiceImpl implements UploadService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif","image/jpg","image/png");
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Autowired
    private FastFileStorageClient fileStorageClient;

    @Override
    public String uploadFile(MultipartFile file) {

        String filename = file.getOriginalFilename();
        String contentType=file.getContentType();
        //校验文件的类型
        //String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            LOGGER.info("文件类型不合法：{}", filename);
            return null;
        }
        //检验文件的内容：确保文件是图片
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage==null){
                LOGGER.info("文件内容不合法：{}", filename);
                return null;
            }
            //file.transferTo(new File("D:\\test\\"+filename));
            //返回url用于回显
            //上传图片到fastdfs
            String type = StringUtils.substringAfterLast(filename, ".");
            StorePath storePath = this.fileStorageClient.uploadFile(file.getInputStream(), file.getSize(), type, null);
            String fullPath = storePath.getFullPath();

            return "http://image.leyou.com/"+fullPath;

        }catch (Exception e) {
            LOGGER.info("服务器内部错误：{}"+ filename);
            e.printStackTrace();
        }
        return null;
    }
}
